<template>
  <editor v-model="myValue" :init="init" :disabled="disabled" :id="tinymceId" />
</template>
<script setup lang="ts">
  import { reactive, ref, onMounted, watch } from 'vue';
  import COS from 'cos-js-sdk-v5';
  import tinymce from 'tinymce/tinymce';
  // import 'tinymce/skins/content/default/content.css'
  import Editor from '@tinymce/tinymce-vue';
  import 'tinymce/themes/silver';
  import 'tinymce/themes/silver/theme';
  import 'tinymce/icons/default';
  import 'tinymce/models/dom';

  import 'tinymce/icons/default/icons';
  import 'tinymce/plugins/table';
  import 'tinymce/plugins/lists';
  import 'tinymce/plugins/wordcount';
  import 'tinymce/plugins/code';

  import 'tinymce/skins/ui/oxide/skin.css';
  import 'tinymce/plugins/advlist'; //高级列表
  import 'tinymce/plugins/anchor'; //锚点
  import 'tinymce/plugins/autolink'; //自动链接
  import 'tinymce/plugins/autoresize'; //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
  import 'tinymce/plugins/autosave'; //自动存稿
  import 'tinymce/plugins/charmap'; //特殊字符
  import 'tinymce/plugins/codesample'; //代码示例
  import 'tinymce/plugins/directionality'; //文字方向
  import 'tinymce/plugins/emoticons'; //表情
  import 'tinymce/plugins/fullscreen'; //全屏
  import 'tinymce/plugins/help'; //帮助
  import 'tinymce/plugins/image'; //插入编辑图片
  import 'tinymce/plugins/importcss'; //引入css
  import 'tinymce/plugins/insertdatetime'; //插入日期时间
  import 'tinymce/plugins/link'; //超链接
  import 'tinymce/plugins/media'; //插入编辑媒体
  import 'tinymce/plugins/nonbreaking'; //插入不间断空格
  import 'tinymce/plugins/pagebreak'; //插入分页符
  import 'tinymce/plugins/preview'; //预览
  import 'tinymce/plugins/quickbars'; //快速工具栏
  import 'tinymce/plugins/save'; //保存
  import 'tinymce/plugins/searchreplace'; //查找替换
  // import 'tinymce/plugins/template'; //内容模板
  import 'tinymce/plugins/visualblocks'; //显示元素范围
  import 'tinymce/plugins/visualchars'; //显示不可见字符
  import { getToken, uploadXiuMi } from '@/api/upload/upload';
  let cosConfig = ref<any>({});

  const emits = defineEmits(['getContent']);
  const props = defineProps({
    value: {
      type: String,
      default: () => {
        return '';
      },
    },
    baseUrl: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default: 'lists  table',
    }, //必填
    toolbar: {
      type: [String, Array],
      default:
        'codesample bold italic underline alignleft aligncenter alignright alignjustify | undo redo | formatselect | fontselect | fontsizeselect | forecolor backcolor | bullist numlist outdent indent | lists link table code | removeformat ',
    }, //必填
  });
  //用于接收外部传递进来的富文本
  let myValue = ref(props.value);
  const urls: any = ref([]);
  const fail_img =
    'https://api.xinzhuvip.com/store_style/20200922/d63b4e529edbdf11aefdcde6ee854820.jpeg';

  const tinymceId = ref('vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + ''));
  //定义一个对象 init初始化
  const init = reactive({
    license_key: 'gpl',
    selector: '#' + tinymceId.value, //富文本编辑器的id,
    referrer_policy: 'origin',
    language_url: import.meta.env.VITE_EDITOR_URL + 'tinymce/langs/zh_CN.js', // 语言包的路径，具体路径看自己的项目，文档后面附上中文js文件
    language: 'zh_CN', //语言
    skin_url: import.meta.env.VITE_EDITOR_URL + 'tinymce/skins/ui/oxide', // skin路径，具体路径看自己的项目
    height: 740, //编辑器高度
    width: '100%', //编辑器高度
    branding: false, //是否禁用“Powered by TinyMCE”
    menubar: true, //顶部菜单栏显示
    image_dimensions: false, //去除宽高属性
    plugins:
      'codesample preview searchreplace autolink directionality visualblocks visualchars image link media template table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount autosave',
    toolbar:
      'preview codesample code forecolor backcolor styles directionality fontfamily fontsize searchreplace image  media link alignleft aligncenter alignright template table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount autosave ',
    font_formats:
      'Arial=arial,helvetica,sans-serif; 宋体=SimSun; 微软雅黑=Microsoft Yahei; Impact=impact,chicago;', //字体
    fontsize_formats: '11px 12px 14px 16px 18px 24px 36px 48px 64px 72px', //文字大小
    // paste_convert_word_fake_lists: false, // 插入word文档需要该属性
    paste_data_images: true,
    images_cross_domain: true,
    // eslint-disable-next-line prettier/prettier
    paste_webkit_styles: "all",
    paste_merge_formats: true,
    nonbreaking_force_tab: false,
    paste_auto_cleanup_on_paste: false,
    promotion: false,
    resize: false,
    statusbar: false,
    file_picker_types: 'image media',
    content_css: import.meta.env.VITE_EDITOR_URL + 'tinymce/skins/content/default/content.css', //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
    //图片上传
    paste_preprocess: (_plugin: any, args: any) => {
      let _dom = document.createElement('div');
      _dom.innerHTML = args.content;
      let imgArr = _dom.getElementsByTagName('img');
      if (imgArr.length) {
        for (let i = 0; i < imgArr.length; i++) {
          let src: any = imgArr[i].getAttribute('src');
          if (src.indexOf('blob:') == -1 && src.indexOf('api.xinzhuvip.com') == -1) {
            urls.value.push(imgArr[i].getAttribute('src'));
            imgArr[i].classList.add('replaceImg');
            let domAll: any = _dom.querySelectorAll('.replaceImg')[i];
            imgArr[i].setAttribute(
              'src',
              'https://xinzhu-1301398555.cos.ap-shanghai.myqcloud.com//loading.gif'
            );
            imgArr[i].setAttribute('init-width', domAll.style.width);
            imgArr[i].setAttribute('init-height', domAll.style.height);
            imgArr[i].removeAttribute('crossorigin');
            domAll.style.width = '30px';
            domAll.style.height = '30px';
          }
        }
      }
      args.content = _dom.innerHTML;
      setCopyImg(_dom);
    },

    images_upload_handler: (blobInfo: any) =>
      new Promise((resolve, reject) => {
        if (blobInfo.blob().size / 1024 / 1024 > 2) {
          reject({ message: '上传失败，图片大小请控制在 2M 以内', remove: true })
          return;
        } else {
          let params = new FormData();
          let token: any = localStorage.getItem('token');
          params.append('file', blobInfo.blob());
          params.append('token', token);
          params.append('modular', 'storeProDetailed');

          //图片上传到第三方
          let cos: any = {};
          cos = new COS({
            getAuthorization: function (_options: any, callback: any) {
              callback({
                TmpSecretId: cosConfig.value.credentials.tmpSecretId,
                TmpSecretKey: cosConfig.value.credentials.tmpSecretKey,
                SecurityToken: cosConfig.value.credentials.sessionToken,
                // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                StartTime: cosConfig.value.startTime, // 时间戳，单位秒，如：1580000000
                ExpiredTime: cosConfig.value.expiredTime, // 时间戳，单位秒，如：1580000000
                ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
              });
            },
          });
          let str: string = blobInfo.blob().name;
          let position: number = str.indexOf('.');
          let file_suffix: string = str.substring(position + 1);
          cos.uploadFile(
            {
              Bucket: 'xinzhu-1301398555',
              Region: 'ap-shanghai',
              Key: 'admin/editor/' + generateRandomString(12) + '.' + file_suffix,
              SliceSize: 1024 * 1024 * 10,
              Body: blobInfo.blob(), // 上传文件对象
              onProgress: function (progressData: any) {
                console.log(JSON.stringify(progressData));
              },
            },
            function (err: any, res: any) {
              console.log(err);
              if (res.statusCode == 200) {
                resolve('https://' + res.Location);
              }
              return true;
            }
          );
        }
      }),
    // 文件上传
    file_picker_callback: (callback: any, value: any, meta: any) => {
      if (meta.filetype == 'file') {
        callback('mypage.html', { text: 'My text' });
      }
      console.log(value);
      if (meta.filetype == 'image') {
        callback('myimage.jpg', { alt: 'My alt text' });
      }

      if (meta.filetype == 'media') {
        callback('movie.mp4', { source2: 'alt.ogg', poster: 'image.jpg' });
      }
    },
  });

  watch(
    () => props.value,
    () => {
      myValue.value = props.value;
      emits('getContent', myValue.value);
    }
  );
  //监听富文本中的数据变化
  watch(
    () => myValue.value,
    () => {
      emits('getContent', myValue.value);
    }
  );
  //在onMounted中初始化编辑器
  onMounted(() => {
    tinymce.init({});
    getUploadToken();
  });

  const getUploadToken = () => {
    const response: any = getToken();
    cosConfig.value = response.data;
  };

  function generateRandomString(length: number) {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * characters.length));
    }

    return result;
  }

  const setCopyImg = (_dom: any) => {
    let imgs: any = _dom.querySelectorAll('.replaceImg');
    console.log(urls.value);
    if (urls.value.length == 0) {
      return false;
    }
    let ress: any = tinymce.get(tinymceId.value);
    new Promise(async function (resolve) {
      const response: any = await uploadXiuMi({ source: urls.value });
      console.log(response);
      if (response.code == 200) {
        for (let i = 0; i < imgs.length; i++) {
          imgs[i].setAttribute('src', response.data[i]);
          imgs[i].style.width = '100%';
          imgs[i].style.height = imgs[i].getAttribute('init-height');
          imgs[i].setAttribute('data-mce-src', response.data[i]);
          imgs[i].classList.remove('replaceImg');
        }
        ress.setContent(_dom.innerHTML);
        resolve(_dom.innerHTML); // 将异步操作的结果传递给Promise对象，状态变为fulfilled
      } else {
        for (let i = 0; i < imgs.length; i++) {
          imgs[i].setAttribute('src', fail_img); //_dom.querySelectorAll(".replaceImg")[i]
          imgs[i].style.width = '400px';
          imgs[i].style.height = '300px';
          imgs[i].setAttribute('data-mce-src', fail_img);
          imgs[i].classList.remove('replaceImg');
        }
        ress.setContent(_dom.innerHTML);
        resolve(_dom.innerHTML); // 将异步操作的结果传递给Promise对象，状态变为fulfilled
      }
      urls.value = [];
    });
  };
</script>
